package com.sita.bike.ui.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.sita.bike.R;
import com.sita.bike.support.GlobalContext;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 环形的进度条
 *
 * @author lwz <lwz0316@gmail.com>
 */
public class AudioCircularProgressBar extends View implements AudioManager.AudioStateListener {


    private Paint mPaint = new Paint();
    private RectF mRectF = new RectF();

    private int mBackgroundColor = Color.WHITE;
    private int mPrimaryColor = Color.parseColor("#00a980");
    private float mStrokeWidth = 20F;//设置圆环的宽度
    private Bitmap circuleGreenGraph;//绿色圆形背景图
    private Bitmap circuleGreenForkGraph;//绿色圆形带有白叉的背景图
    public Context context;
    public Timer timer;

    private int mTimerMax = 15 * 1000;
    private int mTimerCounter = 0;
    private final int TIME_DELAY = 200;
    public final int RECORD_READY = 0, RECORDING = 1, RECORD_COMPLETE = 2;
    private int mStatus = RECORD_READY;

    private AudioManager mAudioManager;
    private float mTime;
    private boolean isRecording = false;
    public AudioTimerListener mAudioTimerListener;

    @Override
    public void wellPrepared() {
        mHandler.sendEmptyMessage(MSG_AUDIO_PREPARED);
    }

    /**
     * 进度条改变监听
     * <p/>
     * {@link #onChange(int duration, int progress, float rate)}
     */
    public interface OnProgressChangeListener {
        /**
         * 进度改变事件，当进度条进度改变，就会调用该方法
         *
         * @param duration 总进度
         * @param progress 当前进度
         * @param rate     当前进度与总进度的商 即：rate = (float)progress / duration
         */
        public void onChange(int duration, int progress, float rate);
    }

    private OnProgressChangeListener mOnChangeListener;

    /**
     * 设置进度条改变监听
     *
     * @param l
     */
    public void setOnProgressChangeListener(OnProgressChangeListener l) {
        mOnChangeListener = l;
    }

    public AudioCircularProgressBar(Context context) {
        super(context);
        this.context = context;
    }

    public AudioCircularProgressBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        //mDialogManager=new DialogManager(getContext());

        String dir = Environment.getExternalStorageDirectory() + "/imooc_recorder_audios";
        mAudioManager = AudioManager.getInstance(dir);
        Log.d("AudioRecorderButton", "before");
        mAudioManager.setOnAudioStateListener(this);

        setOnLongClickListener(new OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                Log.d("longclick", "beforeClick");
//                mAudioManager.prepareAudio();
                return false;
            }
        });
    }

    public interface AudioFinishRecorderListener {
        void onFinish(float seconds, String filePath);
    }

    private AudioFinishRecorderListener mListener;

    public void setAudioFinishRecorderListener(AudioFinishRecorderListener listener) {
        mListener = listener;
    }


    private Runnable mGetVoiceLevelRunnable = new Runnable() {

        @Override
        public void run() {
            while (isRecording) {
                Log.d("mGetVoiceLevelRunnable", "before_try");
                try {
                    Thread.sleep(100);
                    mTime += 0.1f;
                    mHandler.sendEmptyMessage(MSG_VOICE_CHANGED);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    private static final int MSG_AUDIO_PREPARED = 0X110;
    private static final int MSG_VOICE_CHANGED = 0X111;
    private static final int MSG_DIALOG_DIMISS = 0X112;
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSG_AUDIO_PREPARED:

                    isRecording = true;
                    Log.d("handleMessage", "beforeThread");

                    new Thread(mGetVoiceLevelRunnable).start();
                    Log.d("handleMessage", "afterThread");
                    break;
                case MSG_VOICE_CHANGED:
                    Log.d("MSG_VOICE_CHANGED", "in");
                    break;
                case MSG_DIALOG_DIMISS:
                    break;

                default:
                    break;
            }
        }
    };


    /**
     * 设置进度条背景的颜色
     */
    public void setBackgroundColor(int color) {
        mBackgroundColor = color;
    }

    /**
     * 设置进度条进度的颜色
     */
    public void setPrimaryColor(int color) {
        mPrimaryColor = color;
    }

    /**
     * 设置环形的宽度
     *
     * @param width
     */
    public void setCircleWidth(float width) {
        mStrokeWidth = width;

    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        circuleGreenGraph = BitmapFactory.decodeResource(GlobalContext.getGlobalContext().getResources(), R.drawable.circle_no_normal);
        circuleGreenForkGraph = BitmapFactory.decodeResource(GlobalContext.getGlobalContext().getResources(), R.drawable.circle_normal);

        int halfWidth = getWidth() / 2;
        int halfHeight = getHeight() / 2;
        int radius = halfWidth < halfHeight ? halfWidth : halfHeight;
        float halfStrokeWidth = mStrokeWidth / 2;

        // 设置画笔
        mPaint.setColor(mBackgroundColor);
        mPaint.setDither(true);
        mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth(mStrokeWidth);
        mPaint.setStyle(Paint.Style.STROKE);    //设置图形为空心

        // 画背景
        canvas.drawCircle(halfWidth, halfHeight, radius - halfStrokeWidth, mPaint);
        // 画当前进度的圆环
        mPaint.setColor(mPrimaryColor);    // 改变画笔颜色
        mRectF.top = halfHeight - radius + halfStrokeWidth;
        mRectF.bottom = halfHeight + radius - halfStrokeWidth;
        mRectF.left = halfWidth - radius + halfStrokeWidth;
        mRectF.right = halfWidth + radius - halfStrokeWidth;
        canvas.drawArc(mRectF, -90, getRateOfProgress() * 360, false, mPaint);

        // 画中心按钮
        mRectF.top += 4 * halfStrokeWidth;
        mRectF.bottom -= 4 * halfStrokeWidth;
        mRectF.left += 4 * halfStrokeWidth;
        mRectF.right -= 4 * halfStrokeWidth;
        if (mStatus == RECORD_READY) {
            canvas.drawBitmap(circuleGreenGraph, null, mRectF, mPaint);
        } else {
            canvas.drawBitmap(circuleGreenForkGraph, null, mRectF, mPaint);
        }
        canvas.save();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                invalidate();
            }
        }
    };

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (mStatus == RECORD_READY) {
                    mStatus = RECORDING;
                    mAudioManager.prepareAudio();
                    startTimer();
                }
                return true;
            case MotionEvent.ACTION_UP:
                if (mStatus == RECORDING) {
                    mStatus = RECORD_COMPLETE;
                    if (mTimerCounter <= mTimerMax) {
                        stopTimer();
                        mAudioManager.release();
                        if (mTimerCounter < 2) {
                            mAudioManager.cancel();
                        } else {
                            mListener.onFinish(mTime, mAudioManager.getCurrentFilePath());
                        }
                    }
                } else if (mStatus == RECORD_COMPLETE) {
                    mStatus = RECORD_READY;
                    resetData();
                    invalidate();
                    mAudioTimerListener.reset();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_CANCEL:
                mAudioManager.cancel();
                break;

        }
        return super.onTouchEvent(event);
    }

    private void startTimer() {
        if (timer == null) {
            timer = new Timer();
        }
        timer.schedule(new TimersTask(), 0, TIME_DELAY);
    }

    private void sendTimerRecycleCount(int timerCounter) {

        mAudioTimerListener.getTime(timerCounter / 1000);

    }

    private void stopTimer() {
        timer.cancel();
        timer.purge();
        timer = null;
    }

    private void resetData() {
        mTimerCounter = 0;
    }

    /**
     * 得到当前的进度的比率
     * <p> 用进度条当前的值 与 进度条的最大值求商 </p>
     *
     * @return
     */
    private float getRateOfProgress() {
        return (float) mTimerCounter / mTimerMax;
    }


    class TimersTask extends TimerTask {

        public TimersTask() {

        }

        @Override
        public void run() {
            if (mTimerCounter <= mTimerMax) {
                handler.sendEmptyMessage(1);
                mTimerCounter = mTimerCounter + TIME_DELAY;
                sendTimerRecycleCount(mTimerCounter);
            } else {
                stopTimer();
                mAudioManager.release();
                mListener.onFinish(mTime, mAudioManager.getCurrentFilePath());
            }

        }
    }

    public interface AudioTimerListener {
        void getTime(int count);

        void reset();
    }

    public void setAudioTimerListener(AudioTimerListener audioTimerListener) {
        this.mAudioTimerListener = audioTimerListener;
    }
}
